package com.clwl.supervise.superviseapp.controller.base;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import com.clwl.supervise.superviseapp.Constants;
import com.clwl.supervise.superviseapp.entity.base.TsUser;
import com.clwl.supervise.superviseapp.entity.result.ResultCode;
import com.clwl.supervise.superviseapp.entity.result.ResultEntity;
import com.clwl.supervise.superviseapp.service.base.SysLoginInfoService;
import com.clwl.supervise.superviseapp.service.base.UserService;
import com.clwl.supervise.superviseapp.util.UserHelper;
import com.clwl.supervise.superviseapp.util.sm4Encryption.SoftEncryption;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 用户相关信息
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    private UserService userService;

    @Autowired
    private RedisTemplate<String, TsUser> userRedisTemplate;

    @Autowired
    private RedisTemplate<String, String> userStatusTemplate;

    @Autowired
    private SysLoginInfoService sysLoginInfoService;

    @PostMapping("login")
    public ResultEntity login(String username, String password,HttpServletRequest request) {
        if (StringUtils.isAnyBlank(username, password)) {
            return ResultEntity.error("用户名和密码不能为空.");
        }
        byte[] fastKey = HexUtil.decodeHex(Constants.LOGIN_MD4_KEY);
        //加密的账号密码等信息
        username = new String(SoftEncryption.decryptBySM4(Base64.decode(username), fastKey).get("bytes", byte[].class)).trim();
        password = new String(SoftEncryption.decryptBySM4(Base64.decode(password), fastKey).get("bytes", byte[].class)).trim();

        //账号密码登录
        TsUser user = userService.selectByUserName(username);
        if (user == null) {
            sysLoginInfoService.insertLoginLog(request,username,"50002","账号不存在!",null);
            return ResultEntity.error("账号不存在");
        }
        if (StringUtils.equals(user.getDisabledStatus(),"1") ) {
            sysLoginInfoService.insertLoginLog(request,username,"50003","用户已被禁用!",null);
            return ResultEntity.error("用户已被禁用");
        }
        String userpass = UserHelper.sha256(password, user.getSalt());
        if (StringUtils.equals(userpass, user.getPassword())) {
            String token = UUID.randomUUID() + "_supervise_app_" + user.getId();
            user.setToken(token);
            //存储用户token
            userRedisTemplate.opsForValue().set(token, user, 12, TimeUnit.HOURS);
            userStatusTemplate.opsForHash().put("user_disabled_status", user.getId().toString(),user.getDisabledStatus() == null ? "0" :user.getDisabledStatus());
            sysLoginInfoService.insertLoginLog(request,username,"00000","登录成功!",user.getDeptId());
            return ResultEntity.success(user);
        } else {
            sysLoginInfoService.insertLoginLog(request,username,"50001","密码错误!",null);
            return ResultEntity.error("密码错误");
        }

    }

    @GetMapping("loginOut")
    public ResultEntity loginOut(HttpServletRequest request) {
        String userToken = request.getHeader("token");//用户token
        if (StringUtils.isBlank(userToken)) {
            return ResultEntity.error("用户未登录！！！");
        }
        TsUser user = userRedisTemplate.opsForValue().get(userToken);
        if (null == user) {
            return ResultEntity.error("非法的token，没有对应用户登录信息");
        }
        userRedisTemplate.opsForValue().getOperations().delete(userToken);
        return ResultEntity.success();
    }

    @PostMapping("checkPassWord")
    public ResultEntity checkPassWord(String password) {
        Long userId = UserHelper.getUserId();
        if (null == userId) {
            return ResultEntity.error("账户未登录");
        }
        byte[] fastKey = HexUtil.decodeHex(Constants.LOGIN_MD4_KEY);
        //加密的密码等信息
        password = new String(SoftEncryption.decryptBySM4(Base64.decode(password), fastKey).get("bytes", byte[].class)).trim();
        //账号密码登录
        TsUser user = userService.selectUserInfo(userId);
        if (user == null) {
            return ResultEntity.error("账号不存在");
        }
        String userpass = UserHelper.sha256(password, user.getSalt());
        if (StringUtils.equals(userpass, user.getPassword())) {
            return ResultEntity.success();
        } else {
            return ResultEntity.error("密码错误");
        }

    }

    @PostMapping("updatePassWord")
    public ResultEntity updatePassWord(String password) {
        Long userId = UserHelper.getUserId();

        if (null == userId) {
            return ResultEntity.error("账户未登录");
        }

        byte[] fastKey = HexUtil.decodeHex(Constants.LOGIN_MD4_KEY);
        //加密的密码等信息
        password = new String(SoftEncryption.decryptBySM4(Base64.decode(password), fastKey).get("bytes", byte[].class)).trim();
        if (StringUtils.isNotBlank(password) && password.length() < 6) {
            return ResultEntity.error("密码长度不能小于6位");
        }
        //账号密码登录
        TsUser user = userService.selectUserInfo(userId);
        if (user == null) {
            return ResultEntity.error("账号不存在");
        }
        String userpass = UserHelper.sha256(password, user.getSalt());
        user.setPassword(userpass);
        boolean flag = userService.updateById(user);
        if (flag) {
            return ResultEntity.success();
        } else {
            return ResultEntity.error("修改失败");
        }

    }

    /**
     * 获取登陆人信息
     *
     * @return
     */
    @GetMapping("/getLoginUserInfo")
    public ResultEntity<TsUser> getLoginUserInfo() {
        Long userId = UserHelper.getUserId();
        TsUser users = userService.selectUserInfo(userId);
        String password = UserHelper.sha256("a123456", users.getSalt());
        if (null == users) {
            return ResultEntity.error("自动登录失败");
        }
        if (StringUtils.equals(users.getDisabledStatus(),"1") ) {
            return ResultEntity.error("用户已被禁用");
        }
        if (users.getPassword().equals(password)) {
            return ResultEntity.error(ResultCode.PASWORD_DETAULT_ERROR);
        }
        return ResultEntity.success(users);
    }

    @GetMapping("/getMyUserInfo")
    public ResultEntity<Map<String, Object>> getMyUserInfo() {
        Map<String, Object> resultMap = userService.getMyUserInfo();
        if (null == resultMap) {
            return ResultEntity.error("获取登录用户信息失败");
        }
        return ResultEntity.success(resultMap);
    }

}
